import React, { useEffect, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import axios from "axios";
import { ListItem } from "../../store/home/homeReducer";
import { NavBar, ActionBar, Popup, Cell, Stepper, Button } from "react-vant";
import { CartO, ChatO, ShopO } from "@react-vant/icons";
import { useCar } from "../../store/hooks";
import { addCarItemCustomCountAction } from "../../store/car/carAction";
import { useDispatch } from "react-redux";
const Index: React.FC = () => {
  const params = useParams<{ id: string }>();
  const id = params.id;
  const [item, setItem] = useState<ListItem | null>(null);
  const navigate = useNavigate();
  const { count } = useCar();
  const [visible, setVisible] = useState(false);
  const [addCount, setAddCount] = useState(1);
  const dispatch = useDispatch();
  const [html, setHtml] = useState('')


  const addCarItemCustomCount = () => {
    dispatch(
      addCarItemCustomCountAction({ item: item as ListItem, count: addCount })
    );
  };
  useEffect(() => {
    const fetchData = async () => {
      const resp = await axios.post("/api/detail", { id });
      setItem(resp.data.data);  
      setHtml(resp.data.html)
    };
    fetchData();
  }, []);
  return (
    <div>
      <NavBar title="详情" onClickLeft={() => navigate(-1)} />
      <div dangerouslySetInnerHTML={{ __html: html }}></div>
      <Popup visible={visible} position="bottom" title="产品参数">
        <Cell
          title="数量"
          value={
            <Stepper
              value={addCount}
              onChange={(v) => setAddCount(v)}
            ></Stepper>
          }
        ></Cell>
        <Button
          block
          type="primary"
          onClick={() => {
            addCarItemCustomCount();
            setVisible(false);
          }}
        >
          加入购物车
        </Button>
      </Popup>
      <ActionBar>
        <ActionBar.Icon
          icon={<ChatO />}
          text="客服"
          onClick={() => console.log("chat click")}
        />
        <ActionBar.Icon
          icon={<CartO />}
          text="购物车"
          badge={{ content: count || "" }}
          onClick={() => navigate("/car")}
        />
        <ActionBar.Icon
          icon={<ShopO />}
          text="店铺"
          onClick={() => console.log("shop click")}
        />
        <ActionBar.Button
          type="danger"
          text="立即购买"
          onClick={() => setVisible(true)}
        />
      </ActionBar>
    </div>
  );
};

export default Index;
